import json
import time
import random
from .models import UserProfile
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View
import hashlib
import jwt
from django.conf import settings
from tools.login_dec import login_check
from tools.sms import YunTongXin
# Create your views here.
class UserView(View):
    def get(self, request, username=None):
        if username:
            try:
                user = UserProfile.objects.get(username)
            except:
                result = {'code': 10103, 'error': '用户不存在'}
                return JsonResponse(result)
            # 1 获取查询字符串中所有的变量名称
            keys = request.GET.keys()
            if keys:
                data = {}
                for k in keys:
                    if k == 'password':
                        continue
                    if hasattr(user, k):
                        data[k] = getattr(user, k)
                result = {'code': 200,
                          'username': username,
                          'data': data}
            else:
                result = {'code': 200,
                          'username': username,
                          'data': {
                              # 'info':user.info,
                              'sign': user.sign,
                              'nickname': user.nickname,
                              'avatar': str(user.avatar)
                          }}
            return JsonResponse(result)
        else:
            return HttpResponse('get users')

    def post(self, request):
        # 如果提交的是字符串，如何拿数据
        # 1 先获取json串
        json_str = request.body
        # 2 将字符串反序列化为对象
        py_obj = json.loads(json_str)
        # 3 获取灭一个数据
        username = py_obj['username']
        email = py_obj['email']
        # password_1 = py_obj['password_1']
        password = py_obj['password']
        phone = py_obj['phone']
        #  print(username, email,
        #       , password, password_1,phone)

        # 1 用户名的检测
        if not username:
            result = {'code': 10100, 'error': '用户名为空'}
            return JsonResponse(result)
        # 2 两次密码要一致     注册页面根据前端，前端没有两次验证
        # if password_1 != password_2:
        #     result = {'code': 10101, 'error': '密码不一致'}
        #     return JsonResponse(result)

        # 3 计算密码的hash值（md5
        md5 = hashlib.md5()
        md5.update(password.encode())
        password_h = md5.hexdigest()

        # 4 数据入库
        # 用try？因为主键是用户名，防止重复
        # UserProfile.objects.create(...

        try:
            UserProfile.objects.create(
                username=username,
                password=password_h,
                email=email,
                phone=phone
            )
        except Exception as e:
            print(e)
            result = {'code': 10102, 'error': '用户名被占用'}
            return JsonResponse(result)
        # 注册成功。意味着完成了创建，并登录
        # 生成token，返回给客户端浏览器存储token
        token = make_token(username)
        # 这里与配置有关，如果报错那就不需要转化
        token = token.decode()
        return JsonResponse({'code': 200,'base':'http://localhost:63342/DaDaShopping', 'username': username,
                             'data': {'token': token}})


def make_token(username, expire=3600 * 24):
    key = settings.JWT_TOKEN_KEY
    now = time.time()
    payload = {'username': username,
               'exp': now + expire}
    return jwt.encode(payload, key)


@login_check
def user_avatar(request, username):
    if request.method != 'POST':
        return HttpResponse('请求方式必须为post')
    # 修改用户头像
    # 1, 查 2，改 3保存
    user = request.myuser
    user.avatar = request.FILES['avatar']
    user.save()
    return JsonResponse({'code': 200})


def sms_view(request):
    json_str = request.body
    py_obj = json.loads(json_str)
    # 获取手机号
    phone = py_obj['phone']
    print(phone)
    # 生成随机验证码
    code = random.randint(1000, 9999)
    print(code)
    # 发送短信验证请求
    x = YunTongXin(settings.MS_ACCOUNT_ID,
                   settings.MS_ACCOUNT_TOKEN,
                   settings.SMS_APP_ID,
                   settings.SMS_TEMPLATE_ID)
